package com.tjec.project.system.service.impl;

import com.tjec.common.constant.AttachmentConstants;
import com.tjec.common.enums.CodeNum;
import com.tjec.common.enums.NumCode;
import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.SFtpUtil;
import com.tjec.common.utils.ServletUtils;
import com.tjec.common.utils.file.FileNetUrl;
import com.tjec.common.utils.poi.ExcelUtil;
import com.tjec.common.utils.poi.ExcelVo;
import com.tjec.common.utils.poi.ImportExcelUtil;
import com.tjec.framework.security.service.TokenService;
import com.tjec.framework.web.domain.AjaxResult;
import com.tjec.project.businessWorkbench.domain.ImportBmsProjectDocCatalog;
import com.tjec.project.system.domain.*;
import com.tjec.project.system.domain.vo.BmsAttachmentVo;
import com.tjec.project.system.mapper.BmsAttachmentMapper;
import com.tjec.project.system.mapper.BmsCategoryAssociatedMapper;
import com.tjec.project.system.mapper.BmsDocCatalogTemplateListMapper;
import com.tjec.project.system.mapper.BmsMdBusinessCategoryMapper;
import com.tjec.project.system.mapper.BmsMdDocCatalogTemplateMapper;
import com.tjec.project.system.service.IBmsAttachmentService;
import com.tjec.project.system.service.IBmsMdDocCatalogTemplateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 项目文档目录模板Service业务层处理
 *
 * @author tjec
 * @date 2020-04-16
 */
@Service
public class BmsMdDocCatalogTemplateServiceImpl implements IBmsMdDocCatalogTemplateService {
    @Autowired
    private BmsMdDocCatalogTemplateMapper bmsMdDocCatalogTemplateMapper;
    @Autowired
    private IBmsAttachmentService iBmsAttachmentService;
    @Autowired
    private BmsAttachmentMapper bmsAttachmentMapper;
    @Autowired
    private BmsCategoryAssociatedMapper bmsCategoryAssociatedMapper;
    @Autowired
    private BmsMdBusinessCategoryMapper bmsMdBusinessCategoryMapper;
    @Autowired
    private SFtpUtil sftp;

    @Autowired
    private TokenService tokenService;
    
    @Autowired
    private BmsDocCatalogTemplateListMapper bmsDocCatalogTemplateListMapper;

    /**
     * 查询项目文档目录模板
     *
     * @param guid 项目文档目录模板ID
     * @return 项目文档目录模板
     */
    @Override
    public BmsMdDocCatalogTemplate selectBmsMdDocCatalogTemplateById(String guid) {
        BmsMdDocCatalogTemplate entity = bmsMdDocCatalogTemplateMapper.selectBmsMdDocCatalogTemplateById(guid);
        if (StringUtils.isNotBlank(entity.getAttachmentId())) {
            entity.setAttachmentList(iBmsAttachmentService.selectBmsAttachmentDownload(entity.getAttachmentId()));
        }
        //业务类型
        List<BmsMdBusinessCategory> bmsMdBusinessCategoryList = bmsMdBusinessCategoryMapper.selectBusinessCategoryByCategoryAssociated(guid, null);
        entity.setBusinessCategoryList(bmsMdBusinessCategoryList);
        //转化guid成List<String>
        List<String> lists= new ArrayList<String>();
        for (BmsMdBusinessCategory bmsMdBusinessCategory:bmsMdBusinessCategoryList) {
            lists.add(bmsMdBusinessCategory.getGuid()) ;
        }
        entity.setBusinessCategoryIds(lists);
        return entity;
    }

    /**
     * 查询项目文档目录模板列表
     *
     * @param bmsMdDocCatalogTemplate 项目文档目录模板
     * @return 项目文档目录模板
     */
    @Override
    public List<BmsMdDocCatalogTemplate> selectBmsMdDocCatalogTemplateList(BmsMdDocCatalogTemplate bmsMdDocCatalogTemplate) {
        List<BmsMdDocCatalogTemplate> list = bmsMdDocCatalogTemplateMapper.selectBmsMdDocCatalogTemplateList(bmsMdDocCatalogTemplate);
        list.forEach(item -> {
            if (StringUtils.isNotBlank(item.getAttachmentId())) {
                item.setAttachmentList(iBmsAttachmentService.selectBmsAttachmentDownload(item.getAttachmentId()));
            }
            item.setBusinessCategoryList(bmsMdBusinessCategoryMapper.selectBusinessCategoryByCategoryAssociated(item.getGuid(),bmsMdDocCatalogTemplate.getBusinessCategoryId()));
        });
        return list;
    }

    /**
     * 新增项目文档目录模板
     *
     * @param bmsMdDocCatalogTemplate 项目文档目录模板
     * @return 结果
     */
    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int insertBmsMdDocCatalogTemplate(BmsMdDocCatalogTemplate bmsMdDocCatalogTemplate) {
        bmsMdDocCatalogTemplate.setCreateTime(DateUtils.getNowDate());
        int ret = bmsMdDocCatalogTemplateMapper.insertBmsMdDocCatalogTemplate(bmsMdDocCatalogTemplate);
        if (ret > -1) {
            updateAttachment(bmsMdDocCatalogTemplate);
            updateBusinessCategory(bmsMdDocCatalogTemplate);
            //插入项目文档目录模板内容
            bmsMdDocCatalogTemplate.setBusinessCategoryId(StringUtils.join(bmsMdDocCatalogTemplate.getBusinessCategoryIds(),","));
            insertBatchDocCatalogList(bmsMdDocCatalogTemplate,"1");
        }
        return ret;
    }
    
    public void insertBatchDocCatalogList(BmsMdDocCatalogTemplate bmsMdDocCatalogTemplate,String flag) {//1:新增，2:修改
    	if(com.tjec.common.utils.StringUtils.isNotBlank(bmsMdDocCatalogTemplate.getAttachmentId())) {
    		//如果是修改，需要判断附件是否变化
    		if("2".equals(flag)) {
    			//获取原来的数据
    			bmsDocCatalogTemplateListMapper.deleteBmsDocCatalogTemplateListByTemplateId(bmsMdDocCatalogTemplate.getGuid());
    		}
    		
    		List<BmsAttachmentVo> attachments = iBmsAttachmentService.selectBmsAttachmentDownload(bmsMdDocCatalogTemplate.getAttachmentId());
    		if (CollectionUtils.isEmpty(attachments)) {
				return;
			}

			StringBuffer sb = new StringBuffer(attachments.get(0).getStoragePath());
			
			File file = null;
			if (attachments.get(0).getStoragePath().startsWith("https://")) {
				file = FileNetUrl.getNetUrlHttps(sb.toString());
			} else {
				file = FileNetUrl.getNetUrlHttp(sb.toString());
			}
			FileInputStream inputStream;
			try {
				inputStream = new FileInputStream(file);
				List<List<Object>> list = ImportExcelUtil.getBankListByExcel(inputStream, "前期咨询-任务管理清单模板文件.xlsx");

				List<BmsDocCatalogTemplateList> bmsDocCatalogTemplateLists = new ArrayList<BmsDocCatalogTemplateList>();
				
				String[] businessTypeIds = StringUtils.split(bmsMdDocCatalogTemplate.getBusinessCategoryId(),",");
				System.out.println("bmsMdDocCatalogTemplate.getBusinessCategoryId()===="+bmsMdDocCatalogTemplate.getBusinessCategoryId());
				for (String string : businessTypeIds) {
					System.out.println("string===="+string);
					for (int i = 0; i < list.size(); i++) {
						BmsDocCatalogTemplateList bmsDocCatalogTemplateList = new BmsDocCatalogTemplateList();
						bmsDocCatalogTemplateList.setCreateBy(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
						bmsDocCatalogTemplateList.setBusinessTypeId(string);
						bmsDocCatalogTemplateList.setTemplateId(bmsMdDocCatalogTemplate.getGuid());
						for (int j = 0; j < list.get(i).size(); j++) {
							if (j == 0) {
								bmsDocCatalogTemplateList.setFirstCatalogName(list.get(i).get(j).toString());
							} else if (j == 1) {
								bmsDocCatalogTemplateList.setSecondCatalogName(list.get(i).get(j).toString());
							} else if (j == 2) {
								bmsDocCatalogTemplateList.setThirdCatalogName(list.get(i).get(j).toString());
							} else if (j == 3) {
								bmsDocCatalogTemplateList.setFourthCatalogName(list.get(i).get(j).toString());
							} else if (j == 4) {
								bmsDocCatalogTemplateList.setFifthCatalogName(list.get(i).get(j).toString());
							} else if (j == 5) {
								bmsDocCatalogTemplateList.setSixthCatalogName(list.get(i).get(j).toString());
							}
						}
						if(com.tjec.common.utils.StringUtils.isNotBlank(bmsDocCatalogTemplateList.getFirstCatalogName())) {
							bmsDocCatalogTemplateLists.add(bmsDocCatalogTemplateList);
						}
					}
				}
				
				bmsDocCatalogTemplateListMapper.insertBmsDocCatalogTemplateLists(bmsDocCatalogTemplateLists);
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    	
    }

    /**
     * 更新业务类别表
     * @param entity
     */
    private void updateBusinessCategory(BmsMdDocCatalogTemplate entity) {
        if(!CollectionUtils.isEmpty(entity.getBusinessCategoryIds())){
            List<String> categoryList = entity.getBusinessCategoryIds();
            //添加关联库的数据  业务类别的关联
            for (String bms:categoryList) {
                BmsCategoryAssociated associated = new BmsCategoryAssociated();
                associated.setCategoryGuid(bms);
                associated.setParentGuid(entity.getGuid());
                associated.setGuid(UUID.randomUUID().toString());
                associated.setFlag(CodeNum.FIVE.getCode());
                bmsCategoryAssociatedMapper.insertBmsCategoryAssociated(associated);
            }
        }
    }

    /**
     * 新增、修改时更新文件表
     *
     * @param entity
     */
    private void updateAttachment(BmsMdDocCatalogTemplate entity) {
        if (StringUtils.isNotBlank(entity.getAttachmentId())) {
            BmsAttachment bmsAttachment = new BmsAttachment();
            bmsAttachment.setGuid(entity.getAttachmentId());
            bmsAttachment.setBizId(entity.getGuid());
            bmsAttachment.setDelFlag(NumCode.ZERO.getCode());
            bmsAttachment.setCategory(AttachmentConstants.PROJECT_DOC);
            iBmsAttachmentService.updateBmsAttachment(bmsAttachment);
        }
    }

    /**
     * 修改项目文档目录模板
     *
     * @param bmsMdDocCatalogTemplate 项目文档目录模板
     * @return 结果
     */
    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updateBmsMdDocCatalogTemplate(BmsMdDocCatalogTemplate bmsMdDocCatalogTemplate) {
        bmsMdDocCatalogTemplate.setUpdateTime(DateUtils.getNowDate());
        int ret = bmsMdDocCatalogTemplateMapper.updateBmsMdDocCatalogTemplate(bmsMdDocCatalogTemplate);
        if (ret > -1) {
            bmsAttachmentMapper.updateBmsAttachmentByBizId(new String[]{bmsMdDocCatalogTemplate.getGuid()}, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
            updateAttachment(bmsMdDocCatalogTemplate);

            //对业务类别进行修改先删除在重现添加
            bmsCategoryAssociatedMapper.deleteBmsCategoryAssociatedByParentId(bmsMdDocCatalogTemplate.getGuid());
            updateBusinessCategory(bmsMdDocCatalogTemplate);
            
            bmsMdDocCatalogTemplate.setBusinessCategoryId(StringUtils.join(bmsMdDocCatalogTemplate.getBusinessCategoryIds(),","));
            insertBatchDocCatalogList(bmsMdDocCatalogTemplate,"2");
        }
        return ret;
    }

    /**
     * 批量删除项目文档目录模板
     *
     * @param guids 需要删除的项目文档目录模板ID
     * @return 结果
     */
    @Override
    public int deleteBmsMdDocCatalogTemplateByIds(String[] guids) {
    	bmsDocCatalogTemplateListMapper.deleteBmsDocCatalogTemplateListByTemplateIds(guids);
        return bmsMdDocCatalogTemplateMapper.deleteBmsMdDocCatalogTemplateByIds(guids);
    }

    /**
     * 删除项目文档目录模板信息
     *
     * @param guid 项目文档目录模板ID
     * @return 结果
     */
    @Override
    public int deleteBmsMdDocCatalogTemplateById(String guid) {
        return bmsMdDocCatalogTemplateMapper.deleteBmsMdDocCatalogTemplateById(guid);
    }

    @Override
    public AjaxResult validation(String fileUrl) throws Exception {
        Boolean ret = false;
        String path = fileUrl.substring(0, fileUrl.lastIndexOf("/") + 1);
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
        sftp.connectServer();
        InputStream in = sftp.download(path, fileName);
        //InputStream in = new FileInputStream(fileUrl);
        ExcelUtil<ExcelVo> util = new ExcelUtil<ExcelVo>(ExcelVo.class);
        List<ExcelVo> list = util.toList(in, fileName, 0, 6);
        //数据校验
        if (!CollectionUtils.isEmpty(list)) {
            //一级列表
            if (list.stream().anyMatch(a -> StringUtils.isBlank(a.getString1()))) {
                return AjaxResult.error("一级目录为必填项，不能为空");
            }

            //一级列表
            List<String> firstList = list.stream().filter(a -> StringUtils.isBlank(a.getString2()) && StringUtils.isNotBlank(a.getString1())).map(ExcelVo::getString1).collect(Collectors.toList());
            //二级目录列表
            List<ExcelVo> secondDirectoryList = list.stream().filter(a -> StringUtils.isNotBlank(a.getString2())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(secondDirectoryList)) {
                for (ExcelVo vo : secondDirectoryList) {
                    if (!firstList.contains(vo.getString1())) {
                        return AjaxResult.error("登记二级目录时，必须填写此项目录所属的一级目录");
                    }
                }
            }
            //二级列表
            List<String> secondList = list.stream().filter(a -> StringUtils.isBlank(a.getString3()) && StringUtils.isNotBlank(a.getString2())).map(ExcelVo::getString2).collect(Collectors.toList());
            //三级目录列表
            List<ExcelVo> thirdDirectoryList = list.stream().filter(a -> StringUtils.isNotBlank(a.getString3())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(thirdDirectoryList)) {
                for (ExcelVo vo : thirdDirectoryList) {
                    if (!secondList.contains(vo.getString2())) {
                        return AjaxResult.error("登记三级目录时，必须填写此项目录所属的二级目录");
                    }
                }
            }
            //三级列表
            List<String> thirdList = list.stream().filter(a -> StringUtils.isBlank(a.getString4()) && StringUtils.isNotBlank(a.getString3())).map(ExcelVo::getString3).collect(Collectors.toList());
            //四级目录列表
            List<ExcelVo> fourthDirectoryList = list.stream().filter(a -> StringUtils.isNotBlank(a.getString4())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(fourthDirectoryList)) {
                for (ExcelVo vo : thirdDirectoryList) {
                    if (!thirdList.contains(vo.getString3())) {
                        return AjaxResult.error("登记四级目录时，必须填写此项目录所属的三级目录");
                    }
                }
            }
            //四级列表
            List<String> fourthList = list.stream().filter(a -> StringUtils.isBlank(a.getString5()) && StringUtils.isNotBlank(a.getString4())).map(ExcelVo::getString4).collect(Collectors.toList());
            //五级目录列表
            List<ExcelVo> fifthDirectoryList = list.stream().filter(a -> StringUtils.isNotBlank(a.getString5())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(thirdDirectoryList)) {
                for (ExcelVo vo : fifthDirectoryList) {
                    if (!fourthList.contains(vo.getString4())) {
                        return AjaxResult.error("登记五级目录时，必须填写此项目录所属的四级目录");
                    }
                }
            }
            //五级列表
            List<String> fifthList = list.stream().filter(a -> StringUtils.isBlank(a.getString6()) && StringUtils.isNotBlank(a.getString5())).map(ExcelVo::getString5).collect(Collectors.toList());
            //六级目录列表
            List<ExcelVo> sixthDirectoryList = list.stream().filter(a -> StringUtils.isNotBlank(a.getString6())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(sixthDirectoryList)) {
                for (ExcelVo vo : thirdDirectoryList) {
                    if (!fifthList.contains(vo.getString5())) {
                        return AjaxResult.error("登记六级目录时，必须填写此项目录所属的五级目录");
                    }
                }
            }
            return AjaxResult.success();
        }
        return AjaxResult.error("模板数据格式不正确，请按要求填写");
    }

	@Override
	public Integer getCatalogCounts(String businessId) {
		return bmsMdDocCatalogTemplateMapper.getCatalogCounts(businessId);
	}
}
